<template>
	<view>
		<u-popup :show="bindPhoneShow" :round="10" mode="center" :closeable="true" @close="closeBindPhone"
			:closeOnClickOverlay="false">
			<!-- #ifdef MP-WEIXIN -->
			<view class="phoneBox">
				<view class="title">绑定手机号</view>
				<view class="sub-title">为了您的账号安全，请及时绑定手机号</view>
				<u-button type="error" open-type="getPhoneNumber" @getphonenumber="decryptPhoneNumber" text="绑定手机号">
				</u-button>
			</view>
			<!-- #endif -->
			<!-- #ifndef MP-WEIXIN -->
			<view class="phoneBox">
				<view class="title">绑定手机号</view>
				<view class="sub-title">为了您的账号安全，请及时绑定手机号</view>
				<view class="formBox">
					<u--form labelPosition="left" :model="form" labelWidth="60" :rules="rules" ref="form1">
						<u-form-item label="手机号" prop="phone" ref="item1">
							<u--input placeholder="请输入手机号" border="surround" maxlength="11" v-model="form.phone"
								@change="changePhone"></u--input>
						</u-form-item>
						<u-form-item label="验证码" prop="code" ref="item1">
							<u-input placeholder="请输入验证码" v-model="form.code">
								<template slot="suffix">
									<u-code ref="uCode" @change="codeChange" seconds="60" changeText="X秒重新获取"
										@start="disabled = true" @end="disabled = false"></u-code>
									<u-button @tap="getCode" :text="tips" type="error" :disabled="disabled"
										size="small"></u-button>
								</template>
							</u-input>
						</u-form-item>
					</u--form>
					<u-button type="error" text="提交" customStyle="margin-top: 10px" @click="submit"
						:loading="btnLoading"></u-button>
				</view>
			</view>
			<!-- #endif -->
		</u-popup>
	</view>
</template>

<script>
	import {
		mapState,
		mapMutations
	} from 'vuex';
	import {
		sendBindPhoneSMS,
		bindPhone
	} from '@/config/api';
	// #ifdef MP
	import {
		getPhoneInfo
	} from '@/config/login';
	// #endif
	import {
		getUserInfo
	} from '@/config/h5Utils';
	export default {
		name: 'f-phone',
		computed: {
			...mapState(['bindPhoneShow']),
		},
		data() {
			return {
				form: {
					phone: "",
					code: ""
				},
				tips: "",
				disabled: true,
				btnLoading: false,
				rules: {
					'phone': [{
							required: true,
							message: '请输入手机号',
							trigger: ['blur', 'change']
						},
						{
							// 自定义验证函数，见上说明
							validator: (rule, value, callback) => {
								// 上面有说，返回true表示校验通过，返回false表示不通过
								// uni.$u.test.mobile()就是返回true或者false的
								return uni.$u.test.mobile(value);
							},
							message: '手机号码不正确',
							// 触发器可以同时用blur和change
							trigger: ['change', 'blur'],
						}
					],
					'code': {
						required: true,
						message: '请输入短信验证码',
						trigger: ['blur', 'change']
					},
				},
				mpCode: ""
			};
		},
		onReady() {
			// #ifndef MP
			// 如果需要兼容微信小程序，并且校验规则中含有方法等，只能通过setRules方法设置规则
			this.$refs.form1.setRules(this.rules)
			// #endif
		},
		watch: {
			// #ifdef MP
			bindPhoneShow(val) {
				// 静默登录
				val && this.getLoginByUnion()
			}
			// #endif
		},
		methods: {
			...mapMutations(['setBindPhonePopupShow']),
			// 微信小程序绑定手机号
			decryptPhoneNumber(e) {
				console.log(e, '授权手机号')
				var that = this
				if (e.detail.errMsg == 'getPhoneNumber:ok') {
					if (e.detail.iv) {
						var userInfo = e.detail;
						userInfo.code = this.mpCode
						getPhoneInfo(userInfo, res => {
							getUserInfo(() => {
								uni.$u.toast('手机号绑定成功');
								this.closeBindPhone();
							}, false);
						});
					} else {
						uni.$u.toast('授权失败');
					}
				} else {
					uni.$u.toast('授权失败');
				}
			},
			// 关闭窗口
			closeBindPhone() {
				this.setBindPhonePopupShow(false);
				this.form = {
					phone: "",
					code: ""
				};
			},
			codeChange(text) {
				this.tips = text;
			},
			getCode() {
				if (this.$refs.uCode.canGetCode) {
					uni.showLoading({
						title: '正在获取验证码'
					});
					const params = {
						phone: this.form.phone
					}
					sendBindPhoneSMS(params, {
						custom: {
							load: false
						}
					}).then((res) => {
						uni.hideLoading();
						// 这里此提示会被this.start()方法中的提示覆盖
						uni.$u.toast('验证码已发送，请注意查收');
						// 通知验证码组件内部开始倒计时
						this.$refs.uCode.start();
					});
				} else {
					uni.$u.toast('倒计时结束后再发送');
				}
			},
			changePhone(e) {
				if (e.length == 11) {
					this.disabled = false;
				} else {
					this.disabled = true;
				}
			},
			submit() {
				// 如果有错误，会在catch中返回报错信息数组，校验通过则在then中返回true
				this.$refs.form1.validate().then(res => {
					this.btnLoading = true;
					const {
						code,
						phone
					} = this.form;
					const params = {
						code,
						phone
					}
					bindPhone(params).then((res) => {
						getUserInfo(() => {
							uni.$u.toast('手机号绑定成功');
							this.closeBindPhone();
							this.btnLoading = false;
						}, false);
					}).catch(() => {
						this.btnLoading = false;
					})
				}).catch(errors => {

				});
			},
			// 静默登录：就是已经登录过的用户，被迫下线。调用此接口快速登录
			getLoginByUnion() {
				console.log("自动静默登录--自定义接口--")
				var that = this
				uni.login({
					success(res) {
						console.log(res, "获取code")
						that.mpCode = res.code
					}
				})
			}
		}
	}
</script>

<style lang="scss" scoped>
	.phoneBox {
		width: 600rpx;
		padding: 50rpx;

		.title {
			font-size: 30rpx;
		}

		.sub-title {
			padding: 20rpx 0;
			color: #999;
		}

		.formBox {}
	}
</style>
